/* eslint no-underscore-dangle: 0 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Table, Pagination, Icon, Message, Grid, Dialog, DatePicker, Field, Input } from '@alifd/next';
import IceContainer from '@icedesign/container';
import axios from '../../../../instances/request';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
const moment = require('moment');
import InspectionWeekDialog from './InspectionWeekDialog';

const { Row, Col } = Grid;

export default class InspectionWeekTable extends Component {
  field = new Field(this);    // 实例创建
  static displayName = 'InspectionWeekTable';

  static propTypes = {
    limit: PropTypes.number,
    type: PropTypes.string,
    title: PropTypes.string,
  };

  static defaultProps = {
    limit: 8,
  };

  constructor(props) {
    super(props);
    this.state = {
      equipmentList: [],
      tableData: {
        totalCount: 0,
        pageSize: this.props.limit,
        currentPage: 1,
        list: [],
        __loading: false,
      },
      createdAtStart: new Date().getTime(),  // 列表被获取的时间
      value: {
        timeScope: moment(),  // 早上几点上班就减去几个小时即可
      },
      abnormalRecord: '',
    };
  }

  async addOrUpdateInspectionRecord({ id, records }) {
    let url = id == null || id === undefined ? '/inspectionRecord/add' : '/inspectionRecord/update';
    let res = await axios.post(url,{
      id,
      records,
    }).catch((err) => {
      Message.error(`添加或更新巡视记录接口${err}`);
      return Promise.reject(err);
    });
    console.log("添加或更新巡视记录接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`添加或更新巡视记录接口code${code}`);
        return;
    }
  }

  async deleteInspectionRecord({ id }) {
    let res = await axios.post('/inspectionRecord/delete', {
      id,
    }).catch((err) => {
      Message.error(`删除巡视记录接口${err}`);
      return Promise.reject((err));
    });
    console.log("删除巡视记录接口",res);

    let { code, msg } = res.data;
    switch (code) {
      case 0:
        await this.fetchData({ page: this.state.tableData.currentPage });
        break;
      default:
        Message.error(`删除巡视记录接口code${code}`);
        return;
    }
  }

  // todo: 这里不应该将数据请求与返回和组件绑定在一起的，这样做是错误的，应该是数据请求单独是一个函数，组件变换又是一个函数
  async fetchData ({ page, timeScope }) {
    const tableData = this.state.tableData;
    tableData.__loading = true;

    this.setState({ tableData }, async function() {
      let res = await axios.post('/inspectionRecord/list', {
        limit: this.props.limit,
        page: page,
        type: this.props.type,
        timeScope: timeScope ? timeScope.unix() : moment().unix(),  // 传unix时间戳
      }).catch((err) => {
        Message.error(`巡视记录列表接口${err}`);
        return Promise.reject(err);
      });

      console.log("巡视记录列表接口", res);

      let { code, msg } = res.data;
      switch (code) {
        case 0:
          let { inspectionRecords, totalCount, count } = msg;
          const tableData = this.state.tableData;
          tableData.list = inspectionRecords;
          tableData.totalCount = totalCount;
          tableData.__loading = false;
          this.setState({
            tableData,
            createdAtStart: new Date().getTime(),  // 列表被获取时的时间
          });
          break;
        default:
          Message.error(`巡视记录列表接口code${code}`);
          return;
      }
    });
  };

  hookInspectionWeekDialog({equipmentList = [], records = [], id}) {
    InspectionWeekDialog.show({
      value: {
        records,
        equipmentList,
        id,
      },
      onOk: (value) => {
        let { id, records } = value;
        // 添加数据
        return this.addOrUpdateInspectionRecord({
          id,
          records,
        }).then(() => {
          InspectionWeekDialog.hide();
          Message.success("修改巡视记录成功");
        });
      },
      onClose: () => {
        InspectionWeekDialog.hide();
      },
      onCancel: () => {
        InspectionWeekDialog.hide();
      },
    });
  }

  editItem = (row, e) => {
    e.preventDefault();
    this.hookInspectionWeekDialog({
      equipmentList: this.state.equipmentList,
      records: row.records,
      id: row.id,
    });
  };

  deleteItem = (record, e) => {
    e.preventDefault();
    console.log(record);
    let dialog = Dialog.confirm({
      title: '删除确认',
      content: '您确认删除这一条目吗？',
      onOk: () => {
        return this.deleteInspectionRecord({ id: record.id }).then(() => {
          dialog.hide();
          Message.success("删除成功");
        });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  };

  renderOperations = (value, index, record) => {
    return (
      record.status === 'uncheck' &&
      <div className="operation-table-operation">
        <span
          onClick={this.editItem.bind(this, record)}
          title="编辑"
          style={styles.operBtn}
        >
          <Icon size="xs" type="edit" />
        </span>
        <span
          onClick={this.deleteItem.bind(this, record)}
          title="删除"
          style={styles.operBtn}
        >
          <Icon size="xs" type="close" />
        </span>
      </div>
    );
  };

  changePage = (currentPage) => {
    const tableData = this.state.tableData;
    tableData.currentPage = currentPage;
    this.setState({
      tableData
    },() => {
      this.fetchData({ page: currentPage });
    });
  };

  addInspectionRecord = () => {
    this.hookInspectionWeekDialog({
      equipmentList: this.state.equipmentList,
      records: []
    });
  };

  /**
   * 得到设备列表
   * @param page
   * @param limit
   * @return {Promise<{totalCount, equipmentList, count}>}
   */
  async getEquipmentList({ page = 1, limit = -1 }) {
    const res = await axios
      .post('/equipment/list', {
        page: page,
        limit: limit,
        type: this.props.type,
      });
    let { code, msg } = res.data;
    if( code !== 0 ) {
      throw new Error(`获取设备列表接口返回code为${code}`);
    }
    let { totalCount, equipmentList, count } = msg;
    return {
      totalCount,
      equipmentList,
      count,
    }
  }

  async componentDidMount() {
    let { equipmentList } = await this.getEquipmentList({ limit: -1 });
    await this.fetchData({ page: 1});
    this.setState({
      equipmentList
    });

  }

  /**
   * 渲染每一行的数据，这里逻辑非常容易出错，应该让后端把数据顺序都处理好，以最方便的形式返回给前端
   * @param value
   * @param index
   * @param row
   * @return {string}
   */
  renderInspectionData(value, index, row) {
    return row.records[0] ? row.records[0].equipmentName : '';
  }

  renderStatus(value, index, record) {
    switch(record.status) {
      case 'uncheck':
        return '未确认';
      case 'checked':
        return '已确认';
      case 'inspected':
        return '已审核';
    }
  }

  confirmRecord(e) {
    e.preventDefault();
    let dialog = Dialog.confirm({
      content: '您签字确认提交所有记录吗？',
      onOk: () => {
        return axios.post('/inspectionRecord/confirm',{
          timeScope: this.state.value.timeScope.unix(),
          createdAtStart: this.state.createdAtStart,
          type: this.props.type,
        }).then((res) => {
          let {code} = res.data;
          Message.success('确认成功');
          this.fetchData({
            page: 1,
            timeScope: this.state.timeScope
          }).then(() => {
            dialog.hide();
          });
        });
      },
      onCancel: () => {
        dialog.hide();
      }
    });
  }

  addAbnormalRecord(e) {
    e.preventDefault();

    let dialog = Dialog.show({
      title: '填写当天异常记录',
      content: (
        <div style={{ padding: '10px 15px'}}>
          <Input.TextArea style={{width: '300px'}}  onChange={function(value) {
            this.setState({
              abnormalRecord: value,
            })
          }.bind(this)}/>
        </div>
      ),
      onOk: () => {
        return axios.post('/inspectionRecord/abnormal/add', {
          abnormalRecord: this.state.abnormalRecord,
          timeScope: this.state.value.timeScope.unix(),
          type: this.props.type,
        }).then((res) => {
          let {code} = res.data;
          this.setState({
            abnormalRecord: '',  // 重置
          });
          Message.success('提交异常记录成功');
          dialog.hide();
        });
      },
      onCancel: () => {
        dialog.hide();
      }
    })
  }

  formChange(value) {
    let timeScope = value.timeScope;
    this.fetchData({
      page: 1,
      timeScope,
    });
  }

  changeDay(action) {
    let newTimeScope = action === 'before' ? this.state.value.timeScope.subtract(1, 'd') : this.state.value.timeScope.add(1, 'd');
    this.setState({
      value: {
        timeScope: newTimeScope,
      }
    }, () => {
      this.fetchData({
        page: 1,
        timeScope: newTimeScope,
      });
    });
  }

  renderEquipmentState(value, index, row) {
    return row.records[0]? row.records[0].equipmentState : '';
  }

  render() {
    const tableData = this.state.tableData;

    return (
      <div className="operation-table">
        <IceContainer style={styles.cardContainer}>
          <Row>
            <Col>
              <div className="operation-table-title" style={styles.operationTableTitle}>
                { this.props.title }
              </div>
            </Col>
            <Col>
              <IceFormBinderWrapper
                value={this.state.value}
                onChange={this.formChange}
                ref="form"
              >
              <div style={styles.formItem}>
                <span style={styles.formLabel}>日期：</span>
                <IceFormBinder triggerType="onBlur" name="timeScope">
                  <DatePicker size="medium"/>
                </IceFormBinder>
                <ul style={{ height: '24px', lineHeight: '12px', marginLeft: '0px' }}>
                  <li style={{ cursor: 'pointer' }} onClick={this.changeDay.bind(this, 'before')}>
                    <Icon style={{ fontWeight: 'bold', color:'#C4C6AF',}} type="arrow-up" size='xs' />
                  </li>
                  <li style={{ cursor: 'pointer' }} onClick={this.changeDay.bind(this, 'next')}>
                    <Icon style={{ fontWeight: 'bold', color:'#C4C6AF', }} type="arrow-down" size='xs' />
                  </li>
                </ul>
                <div style={styles.formError}>
                  <IceFormError name="timeScope" />
                </div>
              </div>
              </IceFormBinderWrapper>
            </Col>
          </Row>
          <Row>
            <Col>
              <Button style={{
                ...styles.addButton,
                backgroundColor: 'green',
              }} type='primary' >导出到Excel</Button>
              <Button style={styles.addButton} type='primary' onClick={this.addInspectionRecord}>添加巡视记录</Button>
              <Button style={styles.addButton} type='secondary' onClick={this.confirmRecord.bind(this)}>确认记录</Button>
              <Button style={styles.addButton} type='primary' shape="warning" onClick={this.addAbnormalRecord.bind(this)}>添加异常记录</Button>
              {/*{*/}
                {/*this.state.value.timeScope.isSame(moment(), 'd') && */}
                {/*<Button style={styles.addButton} type='primary' onClick={this.addInspectionRecord}>添加巡视记录</Button>*/}
              {/*}*/}
              {/*{*/}
                {/*this.state.value.timeScope.isSame(moment(), 'd') && */}
                {/*<Button style={styles.addButton} type='secondary' onClick={this.confirmRecord.bind(this)}>确认记录</Button>*/}
              {/*}*/}
              {/*{*/}
                {/*this.state.value.timeScope.isSame(moment(), 'd') && */}
                {/*<Button style={styles.addButton} type='primary' shape="warning" onClick={this.addAbnormalRecord.bind(this)}>添加异常记录</Button>*/}
              {/*}*/}
            </Col>
          </Row>
          <Table
            dataSource={tableData.list}
            loading={tableData.__loading}
            className="basic-table"
            hasBorder={false}
            primaryKey="key"
            style={{ textAlign: 'center' }}
          >
            <Table.Column
              title='巡视时间'
              width={100}
              align='center'
              key='key'
              dataIndex='createdTime'
            />
            <Table.Column
              title='巡视人'
              width={100}
              align='center'
              key='key'
              dataIndex='username'
            />
            <Table.Column
              title='巡视人'
              width={100}
              align='center'
              key='key'
              dataIndex='teamName'
            />
            <Table.Column
              title='设备名称'
              width={80}
              align='center'
              key='key'
              cell={this.renderInspectionData.bind(this)}
            />
            <Table.Column
              title='设备状态'
              width={100}
              align='center'
              key='key'
              cell={this.renderEquipmentState}
            />
            <Table.Column
              title='记录状态'
              width={100}
              align='center'
              key='key'
              cell={this.renderStatus}
            />
            <Table.Column
              title='操作'
              width={150}
              align='center'
              key='key'
              cell={this.renderOperations}
            />
          </Table>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  cardContainer: {
    padding: '10px 10px 20px 10px',
  },
  titleCol: {
    display: 'flex',
    flexDirection: 'row',
  },
  titleText: {
    marginLeft: '10px',
    lineHeight: '20px',
  },
  operBtn: {
    display: 'inline-block',
    width: '24px',
    height: '24px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '24px',
    marginRight: '6px',
  },
  paginationContainer: {
    textAlign: 'right',
    paddingTop: '26px',
  },
  operationTableTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    fontColor: 'black',
    height: '32px',
    lineHeight: '30px',
    margin: '15px 0 10px 20px',
    paddingLeft: '12px',
    borderLeft: '4px solid rgb(102, 102, 102)',
  },
  addButton: {
    margin: '5px 10px 15px 5px',
    float: 'right',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 40px',
    float: 'right',
  },
  formLabel: {
    minWidth: '60px',
  },
};
